package com.example.esp8266.activity.utile;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class SocketLink {
    private String charset = "utf-8";
    public Socket mSocket;
    public OutputStream out;
    public InputStream inp;
    public BufferedReader mBufferedReader;
    public boolean isStart = false;
    private Timer mTimer;
    private ReceiveDataTask mReceiveDataTask;
    private ReadThread readThread=null;
    public void openSerialPort(final String ip, final int port) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mSocket = new Socket(ip, port);
                    System.out.println(mSocket+"socket地址----");
                    out = mSocket.getOutputStream();
                    inp = mSocket.getInputStream();
//                    mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                    System.out.println("连接建立成功");

                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("连接失败");
                }
//                isStart = true;

                getPort();
            }
        }).start();
    }
    public SocketLink() {
    }
    // 发送 JSON 格式
    public void sendJson(String jsonData){
        final byte[]  sendjson = jsonData.getBytes();
        if (jsonData !=null && out!=null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        out.write(sendjson);
                        out.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    //发送指令
    public void send(String data){
        final byte[] sendData = DataUtils.HexToByteArr(data);
        if (data!=null && out!=null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        out.write(sendData);
                        out.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
//   发送 GPS信息
    public void sendString(String data){
        final byte[] sendData = data.getBytes();
        if (data!=null && out!=null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        out.write(sendData);
                        out.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }


    public void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mReceiveDataTask == null) {
            mReceiveDataTask = new ReceiveDataTask();
        }
        mTimer.schedule(mReceiveDataTask, 0, 10);
    }

    private class ReceiveDataTask extends TimerTask {
        @Override
        public void run() {
            try {
                if (mBufferedReader != null && (mBufferedReader.ready())) {
                    char[] readbuff = new char[100];
                    byte[] readByte = new byte[100];
//                    mBufferedReader.read(readbuff, 0, readbuff.length);
                    int size = mBufferedReader.read(readbuff, 0, readbuff.length);
                    String tempStrng = String.valueOf(readbuff);
                    readByte = tempStrng.getBytes();
                    String read = DataUtils.ByteArrToHex(readByte, 0, size);
                    EventBus.getDefault().post(read);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void getPort() {
        if (readThread == null) {
            readThread = new ReadThread();
        }
        readThread.start();
    }
    private class ReadThread extends Thread{
        public ReadThread(){
        }
        @Override
        public void run() {
            System.out.println("----size-------");
            while(true) {
//                if (inp == null) {
//                    return;
//                }
//                    byte[] readData = new byte[1024];
//                    try {
//                        int size = inp.read(readData);
//                        System.out.println("****size*****"+size);
//                        if (size > 0){
//                            String receivedData2 = new String(readData, StandardCharsets.UTF_8);
//                            System.out.println("----接接接----"+receivedData2+"-jies--");
//                        }
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }


                InputStreamReader inp2 = null;
                BufferedInputStream bufferedInputStream = null;
                try {
                    if (mSocket != null && mSocket.isConnected()) {
                        //shutdownOutput()不加则会阻塞
//                        mSocket.shutdownOutput();
                    }
                    while (true) {
                        System.out.println("----size-------");
                        //接收服务端返回数据流
                        if (mSocket != null && mSocket.isConnected()) {
//                            LogUtil.debug("socket正在监听端口数据，本地端口号：" + socket.getLocalPort()+"，服务器端口号："+socket.getPort());
                            DataInputStream dataInputStream = new DataInputStream(mSocket.getInputStream());
                            inp2 = new InputStreamReader(dataInputStream, charset);
//                            if (inp2 == null) {
//                                continue;
//                            }
                            StringBuilder sb = new StringBuilder();
                            int count = 0;
                            char[] buf = new char[1024];
                            //一次性接收到所有数据，把每个包的字节拼接在一起，然后统一转为字符串
                            while ((count = inp2.read(buf, 0, buf.length)) > -1) {
                                sb.append(buf, 0, count);
                                if (count < 1024) {
                                    break;
                                }
                            }
                            String data=sb.toString();
                            if(data.isEmpty()){
                                return;
                            }
                            System.out.println("socket接收到服务端返回的数据：" + data);
                            EventBus.getDefault().post(data);

                        }
                    }
                }catch (Exception e){

                }





            }
        }
    }
}
